package com.liuyongsheng.teafile.service;

import com.liuyongsheng.teafile.util.FileStorageUtil;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * PDF转换服务
 */
@Service
public class PdfConversionService {

    @Autowired
    private FileStorageUtil fileStorageUtil;

    /**
     * 将PDF转换为图片
     * @param pdfBytes PDF文件字节数组
     * @param originalFileName 原始文件名
     * @return 图片URL列表
     * @throws IOException 文件处理异常
     */
    public List<String> convertPdfToImages(byte[] pdfBytes, String originalFileName) throws IOException {
        List<String> imageUrls = new ArrayList<>();
        
        try (PDDocument document = PDDocument.load(pdfBytes)) {
            PDFRenderer pdfRenderer = new PDFRenderer(document);
            
            // 逐页转换PDF
            for (int page = 0; page < document.getNumberOfPages(); ++page) {
                // 渲染为300DPI图片
                BufferedImage image = pdfRenderer.renderImageWithDPI(page, 300);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(image, "png", baos);
                
                // 生成图片文件名
                String imageName = originalFileName.replace(".pdf", "_page_" + (page + 1) + ".png");
                // 存储图片并获取URL
                String storedFilePath = fileStorageUtil.storeImage(baos.toByteArray(), imageName);
                imageUrls.add(fileStorageUtil.getImageUrl(storedFilePath));
            }
        }
        
        return imageUrls;
    }

}
